#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：turbo 
@File    ：startapp.py
@Author  ：赵加响
@Date    ：2024/6/19 15:50 
@Desc    ：重写startapp命令，在原始命令基础上多增加serializers.py、filters.py、urls.py文件以及locale目录
"""
import os
from django.core.management.commands.startapp import Command as BaseStartAppCommand


class Command(BaseStartAppCommand):
    help = 'A custom startapp command to add custom files and directories'

    def handle(self, **options):
        app_name = options.get('name')
        target = options.get('directory') or os.getcwd()
        self.stdout.write(target)
        # 使用 call_command 来调用原始的 startapp 命令
        super().handle(**options)

        # 添加额外的 serializers.py 文件
        serializers_path = os.path.join(target, app_name, 'serializers.py')
        with open(serializers_path, 'w') as f:
            f.write("from rest_framework import serializers\n")

        # 添加额外的 filters.py 文件
        filters_path = os.path.join(target, app_name, 'filters.py')
        with open(filters_path, 'w') as f:
            f.write("import django_filters\n")

        # 添加额外的 urls.py 文件
        urls_path = os.path.join(target, app_name, 'urls.py')
        with open(urls_path, 'w') as f:
            f.write("from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n")

        # 创建 locale 目录
        locale_path = os.path.join(target, app_name, 'locale')
        os.makedirs(locale_path, exist_ok=True)

        # 打印成功消息
        self.stdout.write(self.style.SUCCESS(f'Successfully created app {app_name}'))
